package org.je.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author fanyifeng
 * 
 */
public class StringReplacer
{
	private String			src;
	private List<String[]>	list;	// 存放replacement

	/**
	 * @param str
	 */
	public StringReplacer(String str) {
		if (str == null)
			throw new NullPointerException("str-is-null");
		src = str;
		list = new ArrayList<String[]>(6);
	}

	/**
	 * @param token
	 * @param dest
	 */
	public void setReplacement(String token, String dest) {
		if (token == null || dest == null)
			throw new NullPointerException(token == null ? "token-is-null" : "dest-is-null");
		if (token.length() == 0)
			throw new IllegalArgumentException("token.length:0");
		list.add(new String[] { token, dest });
	}

	public String replace() {
		StringBuilder bf = new StringBuilder();
		int off = 0;
		for (int i = 0; i < src.length(); ++i) {
			String[] rp = match(i);
			if (rp != null) {// match success
				if (off < i)
					bf.append(src.substring(off ,i));
				bf.append(rp[1]);
				off = i + rp[0].length();
				i = off - 1;
			}
		}
		if (off < src.length())
			bf.append(src.substring(off));
		return bf.toString();
	}

	// 在众多的replacement中匹配其中一个
	private String[] match(int index) {
		for (int i = 0; i < list.size(); ++i) {
			String[] rp = list.get(i);
			if (index + rp[0].length() <= src.length() && StringUtil.match_not_check(src ,rp[0] ,index))
				return rp;
		}
		return null;
	}
}
